#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aisudptool.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    udpTool(NULL)
{
    ui->setupUi(this);
    udpTool = new AISUdpTool(this);
    connect(udpTool, SIGNAL(receivedUdpData(QByteArray &)), this, SLOT(receivedUdpData(QByteArray &)));
}

MainWindow::~MainWindow()
{
    delete udpTool;
    delete ui;
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    switch (index)
    {
    case 0:
        break;
    case 1:
        if (NULL == udpTool)
        {
            udpTool = new AISUdpTool(this);
        }
        break;
    }
}

void MainWindow::receivedUdpData(QByteArray &byteArray)
{
    ui->teUdpHistoryData->textCursor().insertText(QString(byteArray.data()));

    if (ui->cbUdpScrolling->isChecked())
    {
        ui->teUdpHistoryData->moveCursor(QTextCursor::End);
    }
}

void MainWindow::on_pbUdpListen_clicked()
{
    if (NULL != udpTool)
    {
        QString multiAddress = NULL;
        if (ui->cbUdpEnableMulticast->isChecked())
        {
            multiAddress = ui->leUdpMultiAdress->text();
            if (multiAddress.isEmpty())
            {
                QMessageBox msgBox;
                msgBox.setText("Please input the Multi-Group address or disable it.");
                msgBox.exec();
                return;
            }
        }

        QString portStr = ui->leUdpPort->text();
        if (portStr.isEmpty())
        {
            QMessageBox msgBox;
            msgBox.setText("Please input the Port number, 0 to random.");
            msgBox.exec();
            return;
        }

        udpTool->StartSocket(portStr.toInt(), multiAddress);
    }
}

void MainWindow::on_pbSendData_clicked()
{
    QString sendDataStr = ui->pteUdpSendData->toPlainText();
    QString dstIPAddress = ui->leDstAddress->text();
    QString dstPort = ui->leDstPort->text();
    if (sendDataStr.isEmpty() || dstIPAddress.isEmpty() || dstPort.isEmpty())
    {
        QMessageBox msgBox;
        msgBox.setText("Please input the required info to send data.");
        msgBox.exec();
        return;
    }
    udpTool->SendData(sendDataStr, dstIPAddress, dstPort.toInt());

}

void MainWindow::on_pbClearHistory_clicked()
{
    ui->teUdpHistoryData->setText("");
}
